<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    function fb_login($user_data) {
        // Must Create or Not //
        // No Result. So Create a new one!//
        
        $row = $this->db->select('id,fb_id,firstname,lastname,is_admin')->where('fb_id', $user_data['id'])->get('users')->row_array();
        if (!isset($row['id'])) {
            $data_save = array(
                'fb_id' => $user_data['id'],
                'created_at' => time(),
                'firstname' => $user_data['first_name'],
                'lastname' => $user_data['last_name'],
                'gender' => $user_data['gender'],
                'email' => $user_data['email'],
                'birthday' => date('Y-m-d', strtotime($user_data['birthday']))
            );
            $this->db->insert('users', $data_save);
            $this->_generate_session($this->db->insert_id(), $user_data['id'], $user_data['first_name'].' '.$user_data['lastname']);
        } else { // Existing User //
            $this->_generate_session($row['id'],$row['fb_id'],$row['firstname'].' '.$row['lastname'],$row['is_admin']);
        }
    }

    private function _generate_session($user_id,$fb_id,$fullname, $is_admin = 0) {
        $this->session->set_userdata(array('user_id' => $user_id,'fb_id'=> $fb_id,'fullname'=>$fullname, 'is_admin' => $is_admin));
    }
    
    function logout()
    {
        
        $this->session->sess_destroy();
    }

}
